<template>
  <div class="app-container">
    <!-- tabs -->
    <el-tabs v-model="editableTabsValue" type="border-card" class="mar-b__30" @tab-click="getList(0)">
      <el-tab-pane 
        label="未完成研报"
      >
        <el-col :span="6" >&nbsp;</el-col>
        <el-col :span="6" >&nbsp;</el-col>
        <el-col :span="6" >&nbsp;</el-col>
        <el-col :span="6" >
          <el-col 
            class="mar-r__15" 
            :span="16"
          ><el-input 
            v-model="listQuery.company" 
            placeholder="请输入内容"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button  
              type="primary" 
              icon="plus" 
              @click="getList(listQuery.type)" 
            >查询</el-button>
          </el-col>
        </el-col>
      </el-tab-pane>
      <el-tab-pane 
        label="已完成研报"
        @tab-click="getList(1)"
      > 
        <el-row type="flex" >
          <el-col :span="4">
            <el-select 
              v-model="listQuery.categoryId" 
              placeholder="请选择类别"
              @change="getList"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.categoryName"
                :value="item.categoryId">
              </el-option>
            </el-select>
          </el-col >
          <el-col :span="8">
            <el-date-picker
              v-model="value4"
              type="daterange"
              value-format="yyyy-MM-dd"
              format="yyyy 年 MM 月 dd 日"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :unlink-panels='true'
              @change="getList"
            >
            </el-date-picker>
          </el-col>
          <el-col :span="6">
            <span class="demonstration">完结数量：{{endNum}}篇</span>
            <span class="demonstration">驳回：{{rejectNum}}篇</span>
            <span class="demonstration">通过：{{adoptNum}}篇</span>
          </el-col>
          <el-col :span="6" >
            <el-col class="mar-r__15" :span="16"><el-input v-model="listQuery.company" placeholder="输入公司名称/股票代码"></el-input></el-col>
            <el-col :span="6">
              <el-button  type="primary" icon="plus" @click="getList(listQuery.type)" >查询</el-button>
            </el-col>
          </el-col>
        </el-row>
        
      </el-tab-pane>
    </el-tabs>

    <!-- 表格 -->
    <el-table 
      :data="list" 
      v-loading.body="listLoading" 
      element-loading-text="拼命加载中" 
      border 
      fit
      highlight-current-row
      max-height="1250"
      @row-click="rowClickFun"
    >
      <el-table-column align="center" label="序号" width="80">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)"> </span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="articleTitle" label="文章标题" style="width: 60px;"></el-table-column>
      <el-table-column align="center" prop="username" label="作者ID" style="width: 30px;"></el-table-column>
      <el-table-column align="center" prop="nickname" label="作者名称" style="width: 30px;"></el-table-column>
      <el-table-column align="center" prop="categoryName" label="所属类别" style="width: 10px;"></el-table-column>
      <el-table-column align="center" prop="company" label="所属公司" style="width: 30px;"></el-table-column>
      <el-table-column align="center" prop="companyCode" label="公司代码" style="width: 10px;"></el-table-column>
      <el-table-column
        align="center"
        prop="tag"
        label="文章状态"
      >
        <template slot-scope="scope">
          <el-tag
            :type="dataColorFun(stateCode[scope.row.status]) ? 'success' : 'danger'" 
            close-transition>{{stateCode[scope.row.status]}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updateTime" label="最后更新时间" style="width: 60px;"></el-table-column>
      <el-table-column align="center" label="操作" >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            v-show="listQuery.type == 0"
            v-for="(item, _index) in list[scope.$index].opt" :key="_index"
            @click.stop="handleOpt(scope.$index,item)">{{item}}</el-button>
          <el-button
          type="text"
          size="small"
          v-show="listQuery.type == 1"
          @click.stop="handleOptTab2(scope.$index,item)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="listQuery.currentPage"
      :page-size="10"
      layout="prev, pager, next, jumper"
      :total="totalCount">
    </el-pagination>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form class="small-space" :model="tempArticle" label-position="left" label-width="60px"
               style='width: 300px; margin-left:50px;'>
        <el-form-item label="文章">
          <el-input type="text" v-model="tempArticle.content">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="success" @click="createArticle">创 建</el-button>
        <el-button type="primary" v-else @click="updateArticle">修 改</el-button>
      </div>
    </el-dialog>
    <!-- 上传操作先弹框再上传 -->
    <el-dialog
      title="上传"
      :visible.sync="dialogVisible"
      width="30%"
      >
      <el-upload
        class="upload-demo"
        :action="uploadAddress"
        :data="uploadData"
        :on-success="uploadSuccess"
        :on-error="uploadError"
        :with-credentials='true'
        ref="upload"
        >
        <el-button size="small" type="primary">选择文档</el-button>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="打回修改?"
      :visible.sync="dialogVisibleBackAgainst"
      width="30%"
      >
      <el-input
        type="textarea"
        :rows="2"
        :maxlength='100'
        placeholder="请输入原因"
        v-model="textareaBackAgainst">
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleBackAgainst = false">取 消</el-button>
        <el-button type="primary" @click="backAgainstConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="驳回文章?"
      :visible.sync="dialogVisibleAgainst"
      width="30%"
      >
      <el-input
        type="textarea"
        :rows="2"
        :maxlength='100'
        placeholder="请输入原因"
        v-model="textareaAgainst">
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleAgainst = false">取 消</el-button>
        <el-button type="primary" @click="againstConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {Message} from 'element-ui'
  import { textState, dataColorFun } from '../../utils/state.code'
  export default {
    data() {
      return {
        stateCodes: null,
        uploadAddress: '',
        uploadData: {},//上传附带的数据
        articleId: '',//文章id
        dialogVisibleBackAgainst: false,//打回修改弹框控制
        textareaBackAgainst: '',//打回修改文本域
        dialogVisible: false,//控制上传弹框显示
        dialogVisibleAgainst: false,//驳回文章弹框控制
        textareaAgainst: '',//驳回文章文本
        stateCode: textState,
        editableTabsValue: 0,
        endNum: 0, // 完结数量
        rejectNum: 0, // 驳回
        adoptNum: 0, // 通过
        totalCount: 0, //分页组件--数据总条数
        list: [],//表格的数据
        listLoading: false,//数据加载等待动画
        listQuery: {
          pageNum: 1,//页码
          pageRow: 50,//每页条数
          company: '',
          type: 0,
          startTime: '',
          endTime: '',
        },
        options: [],
        dialogStatus: 'create',
        dialogFormVisible: false,
        textMap: {
          update: '编辑',
          create: '创建文章'
        },
        categoryCode: 0, // 10001  或者  10002 或者 0
        tempArticle: {
          id: "",
          content: ""
        },
        value4: [],
      }
    },
    created() {
      let domian = process.env.NODE_ENV === 'development'?'http://192.168.28.66:8080':location.origin
      this.uploadAddress = domian + '/article/reupload'
      this.getList();
      this.categoryFun()
      this.statistics()
    },
    methods: {
      passConfirm() {
        // 确认通过审核
        this.$confirm('通过审核?', '', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.analystPassVeryfy()
          this.$message({
            type: 'success',
            message: '通过审核成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消通过审核'
          });          
        });
      },
      uploadError(){
        // 上传失败事件

      },
      uploadSuccess(res, file, fileList){
        // 上传成功事件
        if(res.returnCode ==='100'){
          this.message('上传成功!')
          this.dialogVisible= false
          this.getList()
        }else{
          Message({
            message: res.returnMsg,
            type: 'error',
            duration: 3 * 1000
          })
          this.$refs.upload.clearFiles()
        }
      },
      message(mes){
        //提示框
        this.$message({
          showClose: true,
          message: mes,
          type: 'success'
        });
      },
      againstConfirm(){
        // 确认驳回确定按钮
        if(!this.textareaAgainst){
          this.message('原因不能为空!')
          return
        }
        this.dialogVisibleAgainst = false
        this.analystAgainst()
      },
      backAgainstConfirm(){
        // 确认打回修改确定按钮
        if(!this.textareaBackAgainst){
          this.message('原因不能为空!')
          return
        }
        this.dialogVisibleBackAgainst = false
        this.analystBackModify()
      },
      handleOpt(index,item){
        // index:点击的是哪一行，item：具体进行什么操作
        // 操作按钮点击事件
        this.articleId = this.list[index].id
        this.stateCodes = this.list[index].status
        if(item === '下载'){
          this.analystUpload(index)
        }else if(item === '通过审核'){
          this.passConfirm()
        }else if(item === '打回修改'){
          this.dialogVisibleBackAgainst = true
        }else if(item === '修改'){
          this.analystModify()
        }else if(item === '驳回'){
          this.dialogVisibleAgainst = true
        }else if(item === '重新上传'){
          // 单独处理,因为element组件
          this.dialogVisible = true
          this.uploadData = {
            articleId: this.list[index].id,
            articleTitle: this.list[index].articleTitle,
            code: this.stateCodes
          }
        }
      },
      handleOptTab2(index,item){
        this.api({
          url: "/article/download",
          method: "post",
          data: {
            articleId: this.list[index].id,
            type: 0,
            code: this.stateCodes
          }
        }).then(data => {
          this.message('下载成功!')
          location.href = data.path
        })
      },
      analystAgainst(){
        // 驳回
        this.api({
          url: "/article/deny",
          method: "post",
          data: {
            articleId: this.articleId,
            remark: this.textareaAgainst,
            code: this.stateCodes
          }
        }).then(data => {
          this.message('驳回成功!')
          this.getList()
        })
      },
      analystModify(){
        // 修改
        this.api({
          url: "/article/modify",
          method: "post",
          data: {
            articleId: this.articleId,
            code: this.stateCodes
          }
        }).then(data => {
          this.message('修改成功!')
          this.getList()
        })
      },
      analystBackModify(){
        // 打回修改
        this.api({
          url: "/article/backToModify",
          method: "post",
          data: {
            articleId: this.articleId,
            remark: this.textareaBackAgainst,
            code: this.stateCodes
          }
        }).then(data => {
          this.message('打回修改成功!')
          this.getList()
        })
      },
      analystPassVeryfy(){
        // 通过审核
        this.api({
          url: "/article/passAudit",
          method: "post",
          data: {
            articleId: this.articleId,
            code: this.stateCodes
          }
        }).then(data => {
          this.message('通过审核成功!')
          this.getList()
        })
      },
      analystUpload(index){
        // 下载
        this.api({
          url: "/article/download",
          method: "post",
          data: {
            articleId: this.articleId,
            type: '0',
            code: this.stateCodes
          }
        }).then(data => {
          this.message('下载成功!')
          location.href = data.path
        })
      },
      statistics(){
        this.api({
          url: '/article/statistics',
          method:'get'
        }).then(data => {
          this.endNum = data.endNum
          this.rejectNum = data.rejectNum
          this.adoptNum = data.adoptNum
        })
      },
      getList(type) {
        //查询列表
        // if (!this.hasPerm('article:list')) {
        //   return
        // }
        this.statistics()
        if(this.listQuery.categoryId==1){
          this.listQuery.categoryId = ''
        }
        type = this.editableTabsValue
        this.listQuery.type = type
        this.listLoading = true;
        if(type){
          console.log(this.value4);
          
          this.listQuery.startTime = this.value4[0]
          this.listQuery.endTime = this.value4[1]
        }else{
          this.listQuery.startTime = ''
          this.listQuery.endTime = ''
        }
        this.api({  
          url: "/article/compileListArticle",
          method: "get",
          params: this.listQuery
        }).then(data => {
          this.listLoading = false;
          this.list = this.handleLists(data.list)
          this.totalCount = data.totalCount;
        })
      },
      handleLists(list){
        // 遍历所有操作按钮
        if(list.length>0){
          list.map((val,i)=>{
            if(val.operation){
              let _temp = JSON.parse(val.operation)
              val.opt = Object.values(_temp)
            }
          })
        }
        return list
      },
      handleSizeChange(val) {
        //改变每页数量
        this.listQuery.pageRow = val
        this.handleFilter();
      },
      handleCurrentChange(val) {
        //改变页码
        this.listQuery.pageNum = val
        this.getList();
      },
      getIndex($index) {
        //表格序号
        return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
      },
      showCreate() {
        //显示新增对话框
        this.tempArticle.content = "";
        this.dialogStatus = "create"
        this.dialogFormVisible = true
      },
      showUpdate($index) {
        //显示修改对话框
        this.tempArticle.id = this.list[$index].id;
        this.tempArticle.content = this.list[$index].content;
        this.dialogStatus = "update"
        this.dialogFormVisible = true
      },
      createArticle() {
        //保存新文章
        this.api({
          url: "/article/addArticle",
          method: "post",
          data: this.tempArticle
        }).then(() => {
          this.getList();
          this.dialogFormVisible = false
        })
      },
      updateArticle() {
        //修改文章
        this.api({
          url: "/article/updateArticle",
          method: "post",
          data: this.tempArticle
        }).then(() => {
          this.getList();
          this.dialogFormVisible = false
        })
      },
      categoryFun() {
        //类别
        this.api({
          url: "/article/category",
          method: "post",
          data: {
            categoryCode: 0
          }
        }).then((data) => {
          this.options = data.list
        })
      },
      handleDownload(index, row) {
        console.log(index, row);
      },
      handleAdopt(index, row) {
        console.log(index, row);
      },
      handleAgainModify(index, row) {
        console.log(index, row);
      },
      handleReject(index, row) {
        console.log(index, row);
      },
      handleModify(index, row) {
        console.log(index, row);
      },
      handleUpload(index, row) {
        console.log(index, row);
      },
      // 点击进入文章详情
      rowClickFun(row, event, column){
        console.log(this.$route);
        this.$router.push({
          // path: '/user/details',
          // params: {num: row.id},
          // query: query,
          name: 'details'
        })
        sessionStorage.setItem('articleId',row.id)
        sessionStorage.setItem('type','text')
      },
      dataColorFun,
    }
  }
</script>